package api

import (
	"exam12_23/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
	"path/filepath"
	"strings"
	"time"
)

const fileSize = 5 * 1024 * 1024

func Upload(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "文件获取失败",
		})
		return
	}
	open, _ := file.Open()
	defer open.Close()
	if file.Size > fileSize {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "文件过大",
		})
		return
	}

	var map1 = make(map[string]bool)

	map1[".png"] = true
	map1[".jpeg"] = true

	lower := strings.ToLower(filepath.Ext(file.Filename))

	fileName := time.Now().Format("2006-01-02 15:04:05") + lower

	yun, err := pkg.QiNiuYun(open, file, fileName)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "文件上传失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "文件上传成功",
		"data":    yun,
	})

}
